import { createFileRoute } from '@tanstack/react-router'
import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { StorageService } from '../services/storage'
import { SearchBar } from '../components/SearchBar'
import { useSearch, type SearchableItem } from '../hooks/useSearch'

function SearchPage() {
  const [allItems, setAllItems] = useState<SearchableItem[]>([])
  const { searchQuery, setSearchQuery, selectedCategory, setSelectedCategory, filteredItems, categories } = useSearch(allItems)

  useEffect(() => {
    // 加载所有数据并转换为可搜索的格式
    const loadAllData = () => {
      const items: SearchableItem[] = []

      // 加载生活小确幸
      const sweetMoments = StorageService.getSweetMoments() as any[]
      sweetMoments.forEach((moment: any) => {
        items.push({
          id: moment.id,
          title: moment.title,
          content: moment.content,
          category: moment.category,
          date: moment.date,
          type: 'moment'
        })
      })

      // 加载情书
      const letters = StorageService.getLoveLetters() as any[]
      letters.forEach((letter: any) => {
        items.push({
          id: letter.id,
          title: letter.title,
          content: letter.content,
          category: letter.handwritten ? '手写' : '数字',
          date: letter.date,
          type: 'letter'
        })
      })

      // 加载便签
      const notes = StorageService.getStickyNotes() as any[]
      notes.forEach((note: any) => {
        items.push({
          id: note.id,
          title: `${note.author}的便签`,
          content: note.content,
          category: note.author,
          date: note.date,
          type: 'note'
        })
      })

      // 加载愿望清单
      const bucketList = StorageService.getBucketList() as any[]
      bucketList.forEach((item: any) => {
        items.push({
          id: item.id,
          title: item.text,
          content: item.completed ? `已完成: ${item.completionNote || ''}` : '待完成',
          category: item.category,
          date: item.completedDate || item.id,
          type: 'bucket'
        })
      })

      // 加载故事内容
      const storyData = StorageService.getOurStory() as any
      if (storyData.meetingStory?.his) {
        items.push({
          id: 'story-his',
          title: '相遇篇 - 他的视角',
          content: storyData.meetingStory.his,
          category: '我们的故事',
          type: 'story'
        })
      }
      if (storyData.meetingStory?.hers) {
        items.push({
          id: 'story-hers',
          title: '相遇篇 - 她的视角',
          content: storyData.meetingStory.hers,
          category: '我们的故事',
          type: 'story'
        })
      }
      if (storyData.heartMoment) {
        items.push({
          id: 'story-heart',
          title: '心动瞬间',
          content: storyData.heartMoment,
          category: '我们的故事',
          type: 'story'
        })
      }
      if (storyData.timeline) {
        storyData.timeline.forEach((event: any) => {
          items.push({
            id: `timeline-${event.id}`,
            title: event.title,
            content: event.content,
            category: '爱情大事记',
            date: event.date,
            type: 'story'
          })
        })
      }

      setAllItems(items)
    }

    loadAllData()
  }, [])

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'moment': return '✨'
      case 'letter': return '💌'
      case 'note': return '📝'
      case 'bucket': return '🎯'
      case 'story': return '📖'
      default: return '📄'
    }
  }

  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'moment': return '生活小确幸'
      case 'letter': return '情书'
      case 'note': return '便签'
      case 'bucket': return '愿望清单'
      case 'story': return '我们的故事'
      default: return '内容'
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-50 via-white to-rose-50">
      <div className="container mx-auto px-4 py-8">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="max-w-4xl mx-auto"
        >
          {/* 页面标题 */}
          <div className="text-center mb-8">
            <h1 className="text-4xl font-bold text-gray-800 mb-4">
              🔍 搜索我们的回忆
            </h1>
            <p className="text-gray-600">
              在这里搜索所有的美好时光、情书、愿望和故事
            </p>
          </div>

          {/* 搜索栏 */}
          <div className="mb-6">
            <SearchBar
              onSearch={setSearchQuery}
              placeholder="搜索标题、内容、类别或日期..."
              className="mb-4"
            />
            
            {/* 类别筛选 */}
            <div className="flex flex-wrap gap-2">
              <button
                onClick={() => setSelectedCategory('all')}
                className={`px-4 py-2 rounded-full text-sm transition-colors ${
                  selectedCategory === 'all'
                    ? 'bg-pink-500 text-white'
                    : 'bg-white text-gray-700 hover:bg-pink-100'
                }`}
              >
                全部
              </button>
              {categories.map(category => (
                <button
                  key={category}
                  onClick={() => setSelectedCategory(category || '')}
                  className={`px-4 py-2 rounded-full text-sm transition-colors ${
                    selectedCategory === category
                      ? 'bg-pink-500 text-white'
                      : 'bg-white text-gray-700 hover:bg-pink-100'
                  }`}
                >
                  {category}
                </button>
              ))}
            </div>
          </div>

          {/* 搜索结果统计 */}
          <div className="mb-6 text-sm text-gray-600">
            {searchQuery ? (
              <p>
                搜索 "{searchQuery}" 找到 {filteredItems.length} 个结果
                {selectedCategory !== 'all' && ` (在 "${selectedCategory}" 类别中)`}
              </p>
            ) : (
              <p>
                共有 {allItems.length} 个内容
                {selectedCategory !== 'all' && ` (显示 "${selectedCategory}" 类别: ${filteredItems.length} 个)`}
              </p>
            )}
          </div>

          {/* 搜索结果 */}
          <div className="space-y-4">
            {filteredItems.length > 0 ? (
              filteredItems.map((item, index) => (
                <motion.div
                  key={item.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: index * 0.1 }}
                  className="bg-white/80 backdrop-blur-sm rounded-xl p-6 shadow-lg hover:shadow-xl transition-shadow"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center space-x-2">
                      <span className="text-lg">{getTypeIcon(item.type)}</span>
                      <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded-full">
                        {getTypeLabel(item.type)}
                      </span>
                      {item.category && (
                        <span className="text-xs text-pink-600 bg-pink-100 px-2 py-1 rounded-full">
                          {item.category}
                        </span>
                      )}
                    </div>
                    {item.date && (
                      <span className="text-xs text-gray-400">
                        {item.date}
                      </span>
                    )}
                  </div>
                  
                  <h3 className="text-lg font-semibold text-gray-800 mb-2">
                    {item.title}
                  </h3>
                  
                  <p className="text-gray-600 leading-relaxed">
                    {item.content.length > 200 
                      ? `${item.content.substring(0, 200)}...` 
                      : item.content
                    }
                  </p>
                </motion.div>
              ))
            ) : (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="text-center py-12"
              >
                <div className="text-6xl mb-4">🔍</div>
                <h3 className="text-xl font-semibold text-gray-700 mb-2">
                  {searchQuery ? '没有找到匹配的内容' : '开始搜索'}
                </h3>
                <p className="text-gray-500">
                  {searchQuery 
                    ? '尝试使用不同的关键词或清除筛选条件'
                    : '在上方输入关键词来搜索你们的美好回忆'
                  }
                </p>
              </motion.div>
            )}
          </div>
        </motion.div>
      </div>
    </div>
  )
}

export const Route = createFileRoute('/search')({
  component: SearchPage,
})
